package top.cardone.security.shiro.web.filter.authc.impl;

import lombok.extern.log4j.Log4j2;
import org.apache.shiro.web.filter.authc.UserFilter;
import top.cardone.context.util.CodeExceptionUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

/**
 * @author yao hai tao
 * @date 16-2-2
 */
@Log4j2
public class UserFilterImpl extends UserFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (!org.apache.commons.lang3.StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE)) {
            return super.onAccessDenied(request, response);
        }

        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_VALUE);

        try (Writer out = response.getWriter()) {
            String requestURI = getPathWithinApplication(request);

            String json = CodeExceptionUtils.newString(requestURI, "please login system", "请登录系统");

            out.write(json);

            out.flush();
        } catch (java.io.IOException e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }
}